package chapter1;

import algs4.Queue;

public class exercises1_3_1 {

	public static void main(String[] args) {

		//ex_1_3_37(7, 3);
		ex_1_3_41();
	}

	private static void ex_1_3_41()
	{
		Queue<Integer> q = new Queue<Integer>();
		for(int i = 0; i<10; i++)
		{
			q.enqueue(i);
		}

		Queue<Integer> newQ = duplicateQueue(q);
		assert(newQ.size() == q.size());
		assert(newQ.dequeue() == 0);
		assert(q.dequeue() == 0);
		newQ.enqueue(100);
		assert(q.size() == newQ.size() - 1);
	}
	
	private static<T> Queue<T> duplicateQueue(Queue<T> q)
	{
		Queue<T> newQ = new Queue<T>();
		int size = q.size();
		for(int i = 0; i<size; i++)
		{
			T item = q.dequeue();
			newQ.enqueue(item);
			q.enqueue(item);
		}
		return newQ;
	}
	
	private static void ex_1_3_37(int amount, int interval)
	{
		Node<Integer> first = null;
		Node<Integer> previous = null;
		for(int i = 0; i<amount; i++)
		{
			Node<Integer> node = new Node<Integer>();
			node.item = i;
			if(i == 0)
			{
				first = node;
			}
			else if(i == amount - 1)
			{
				node.next = first;
				previous.next = node;
			}
			else
			{
				previous.next = node;
			}
			previous = node;
		}
		
		int remain = amount;
		Node<Integer> current = first;
		while(remain != 0)
		{
			for( int i = 0; i<interval - 2; i++)
			{
				current = current.next;
			}
			
			System.out.println(current.next.item);
			current.next = current.next.next;
			current = current.next;
			remain--;
		}
	}
	
	private static class Node<Item>
	{
		Item item;
		Node<Item> next;
	}
}
